<template>
  <el-dialog v-if="openForm" v-model="openBoole" :close-on-click-modal="false" :title="typeTitle"
    custom-class="mydialog" width="50%" @close="close">
    <el-form ref="openRef" :model="openForm" :rules="rules" label-width="140px" size="small">
      <el-row gutter="40" v-if="typeEdit === 'create'">
        <el-col :span="12">
          <el-form-item label="负责营销职员" prop="headId">
            <el-select v-model="openForm.headId" @change="handleHead" clearable style="width: 100%"
              placeholder="请选择负责营销职员">
              <el-option v-for="item in headData" :key="item.id" :label="item.realName" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="关联营销任务" prop="planName">
<!--            <seller-task ref="sellerTaskRef" :headId="openForm.headId" @confirm="priceConfirm">-->
<!--              <el-select v-model="openForm.planName" :disabled="openForm.headId === undefined" clearable-->
<!--                placeholder="请选择关联营销任务" style="width: 100%" @clear="priceClear" @focus="priceFocus">-->
<!--                <template #empty />-->
<!--              </el-select>-->
<!--            </seller-task>-->

            <el-input
                    ref="refInput"
                    v-model="openForm.saleTaskNo"
                    placeholder="请输入营销任务"
                    clearable
                    @clear="taskClear"
                    @blur="taskBlur"
                    @focus="taskFocus"
            />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="商销客户名称" prop="sellerName">
            <el-autocomplete v-model="openForm.sellerName" :fetch-suggestions="querySearchSeller" :loading="false"
              placeholder="请输入商销客户名称" style="width: 100%" @select="handleSelecSeller" @blur="sellerBlur">
              <template #default="{ item }">
                <div class="distributeName">{{ item.sellerName }}</div>
              </template>
            </el-autocomplete>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="未找到商销客户">
            <el-button type="text" @click="handleTo">新建商销客户</el-button>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="产品通用名" prop="productPopularName">
            <seller-product :searchs="openForm.productPopularName" @confirm="productConfirm"
              :disabled="openForm.allocationAgentId > 0 || disabled">
              <el-input v-model="openForm.productPopularName" :disabled="openForm.allocationAgentId > 0 || disabled" clearable
                placeholder="请输入产品通用名" @clear="productClear" @input="onInput" />
            </seller-product>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="商品名" prop="productName">
            <el-input v-model="openForm.productName" disabled />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="包装规格" prop="packSpecs">
            <el-input v-model="openForm.packSpecs" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="生产厂家" prop="producer">
            <el-input v-model="openForm.producer" disabled />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="交易价" prop="tradePrice">
            <el-input v-model="openForm.tradePrice" clearable placeholder="请输入交易价">
              <template #append>
                <span>元/
                  {{ getLabel('sell_unit', openForm.sellUnit) }}
                </span>
              </template>
            </el-input>
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="其他约定" prop="remark">
            <el-input type="textarea" :rows="2" v-model="openForm.remark" placeholder="请输入其他约定" />
          </el-form-item>
        </el-col>

      </el-row>

      <el-row gutter="40" v-if="typeEdit === 'change'">
        <el-col :span="12">
          <el-form-item label="商销客户名称">
            {{openForm.sellerName}}
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="产品信息">
            {{getProductName(openForm)}}
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="交易价" prop="tradePrice">
            <el-input v-model="openForm.tradePrice" clearable placeholder="请输入交易价">
              <template #append>
                <span>元/
                  {{ getLabel('sell_unit', openForm.sellUnit) }}
                </span>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="负责营销职员" prop="headId">
            <el-select v-model="openForm.headId" clearable @change="handleHead" style="width: 100%"
              placeholder="请选择负责营销职员">
              <el-option v-for="item in headData" :key="item.id" :label="item.realName" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="其他约定" prop="remark">
            <el-input type="textarea" :rows="2" v-model="openForm.remark" placeholder="请输入其他约定" />
          </el-form-item>
        </el-col>
      </el-row>

    </el-form>

    <template #footer>
      <div class="dialog-footer" style="display:flex;justify-content:center;align-items:center;">
        <el-button class="border-btn" size="small" style="margin-right: 20px;" @click="close">取消
        </el-button>
        <el-button class="main-btn" size="small" type="primary" @click="handlSubmit">提交审核
        </el-button>
      </div>
    </template>

    <chanceTaskDialog ref="chanceTask" :head-id="openForm.headId" :task-type="4" @confirm="taskConfirm"/>

  </el-dialog>
</template>

<script>
  import chanceTaskDialog from "../../../modules/chanceTaskDialog";
import {
  getCurrentInstance,
  inject,
  nextTick,
  reactive,
  ref,
  toRefs,
  onMounted,
} from "vue";
import { crmStore } from "@CRM/store";
import { validateVENumber } from "@/utils/validate";
export default {
  name: "AgentDialog",
  components:{chanceTaskDialog},
  props: {
    typeEdit: {
      type: String,
      default: "create",
    },
    taskData:{
      type:Object,
      default:{}
    }
  },
  setup(props, context) {
    //* ************自定义效验**********
    const validateNum = (rule, value, callback) => {
      if (value === "" || value === undefined) {
        callback(new Error("请输入交易价"));
      } else {
        if (validateVENumber(value)) {
          callback(new Error("格式不正确(最多保留两位小数)"));
        } else {
          callback();
        }
      }
    };
    //* ********************************
    const api = inject("api");
    const data = reactive({
      chanceTask:null,
      refInput:null,
      headData: crmStore.getters["company/getHeadOptions"] || [],
      openBoole: false,
      openForm: {
        headId: undefined,
        headName: "",
        planId: undefined,
        planName: "",
        sellerId: undefined,
        sellerName: "",
        productId: undefined,
        productName: "",
        productPopularName: "",
        packSpecs: "",
        producer: "",
        tradePrice: undefined,
        remark: "",
        id: -1,
        sellUnit: "",
        allocationAgentId:0,
          saleTaskId:'',
          saleTaskNo:'',
      },
      rules: {
        headId: [
          { required: true, message: "请选择负责营销职员", trigger: "change" },
        ],
        sellerName: [
          { required: true, message: "请选择商销客户名称", trigger: "change" },
        ],
        productPopularName: [
          { required: true, message: "请输入产品名称", trigger: "blur" },
        ],
        tradePrice: [
          { required: true, validator: validateNum, trigger: "blur" },
        ],
      },
      openRef: null,
      typeTitle: "",
      sellerData: [],
      sellerTaskRef: null,
      disabled: false,
    });

    const currentInstance = getCurrentInstance();

    const handleHead = (val) => {
      var aa = data.headData.find((a) => a.id === val);
      data.openForm.headName = aa?.realName;
    };

    const priceConfirm = (val) => {
      console.log(val);
      data.openForm.planId = val?.planInfo?.id;
      data.openForm.planName = val?.planInfo?.planName;
      data.openForm.productId = val?.planDetail?.productId;
      data.openForm.productName = val?.planDetail?.productName;
      data.openForm.productPopularName = val?.planDetail?.productPopularName;
      data.openForm.packSpecs = val?.planDetail?.packSpecs;
      data.openForm.producer = val?.planDetail?.producer;
      data.openForm.sellUnit = val?.planDetail?.sellUnit;
    };

    const priceFocus = () => {
      data.sellerTaskRef.openPopover();
    };

    const priceClear = () => {
      data.openForm.planId = undefined;
      data.openForm.planName = "";
      data.openForm.productId = undefined;
      data.openForm.productName = "";
      data.openForm.productPopularName = "";
      data.openForm.packSpecs = "";
      data.openForm.producer = "";
      data.disabled = false;
    };

    const taskConfirm = (val) => {
      data.openForm.allocationAgentId = val.id;
      data.openForm.saleTaskId = val.saleTaskId;
        data.openForm.saleTaskNo = val.taskNo;
      data.openForm.productId = val.productId;
      data.openForm.productName = val.productName;
      data.openForm.productPopularName = val.productPopularName;
      data.openForm.packSpecs = val.packSpecs;
      data.openForm.producer = val.producer;
      data.openForm.sellUnit = val.sellUnit;
    }

    const taskBlur = () => {

    }

    const taskFocus = () => {
      // data.chancePop.openPopover()
      data.chanceTask.openDialog()
      data.refInput.blur()
    }

    const taskClear = () => {
      data.openForm.allocationAgentId = 0
      data.openForm.saleTaskId = ''
        data.openForm.saleTaskNo = ''
    }

    const querySearchSeller = async (queryString, cb) => {
      var results = [];
      var res = await api.businessAgreement.BUSINESSAGREEMENT_SHANGPIN_LIST(
        queryString
      );
      if (res.code === 0) {
        results = res.data.list || [];
      }
      cb(results);
    };

    const sellerBlur = () => {
        if (!data.openForm.sellerId){
            data.openForm.sellerName = ''
        }
    }

    const handleSelecSeller = (val) => {
      if (val) {
        data.openForm.sellerName = val.sellerName;
        data.openForm.sellerId = val.id;
      }
    };

    const handleTo = () => {
      window.open(
        "#/marketing/cooperationInformation/shangPin?type='businessAgreement'"
      );
    };

    const productConfirm = (val) => {
      data.openForm.productId = val?.productId || val?.id;
      data.openForm.productName = val?.productName;
      data.openForm.productPopularName = val?.productPopularName;
      data.openForm.packSpecs = val?.packSpecs;
      data.openForm.producer = val?.producer;
      data.openForm.sellUnit = val?.sellUnit;
    };

    const onInput = () => {};

    const productClear = () => {
      data.openForm.productId = undefined;
      data.openForm.productName = "";
      data.openForm.productPopularName = "";
      data.openForm.packSpecs = "";
      data.openForm.producer = "";
    };

    const close = () => {
      data.disabled = true;
      data.openBoole = false;
      data.openRef.clearValidate();
      data.openRef.resetFields();
    };

    const handleRemove = () => {
      data.openForm = {
        headId: undefined,
        headName: "",
        planId: undefined,
        planName: "",
        sellerId: undefined,
        sellerName: "",
        productId: undefined,
        productName: "",
        productPopularName: "",
        packSpecs: "",
        producer: "",
        tradePrice: undefined,
        remark: "",
        id: -1,
        sellUnit: "",
        allocationAgentId:0,
          saleTaskId:'',
          saleTaskNo:''
      };
      data.headData = crmStore.getters["company/getHeadOptions"] || [];
      data.disabled = false
    };

    const open = (title, row) => {
      handleRemove();
      data.typeTitle = title;
      data.openBoole = true;
      data.openForm.headId = crmStore.getters["user/userInfo"]?.ID;
      data.openForm.headName = crmStore.getters["user/userInfo"]?.realName;
      if (row) {
        data.openForm = {
          headId: row?.headId,
          headName: row?.headName,
          planId: row?.planInfo?.id,
          planName: row?.planInfo?.planName,
          sellerId: row?.sellerDetail?.id,
          sellerName: row?.sellerDetail?.sellerName,
          productId: row?.productId,
          productName: row?.productInfoDetail?.productName,
          productPopularName: row?.productInfoDetail?.productPopularName,
          packSpecs: row?.productInfoDetail?.packSpecs,
          producer: row?.productInfoDetail?.producer,
          tradePrice: row?.tradePrice,
          remark: row?.remark,
          id: row?.id,
          sellUnit: row?.productInfoDetail?.sellUnit,
        };
      }

      dealTask()
    };

    const dealTask = () => {
      if (props.taskData && props.taskData.id){
        data.openForm.productId = props.taskData.productId
        data.openForm.productPopularName = props.taskData.productPopularName
        data.openForm.productName = props.taskData.productName
        data.openForm.packSpecs = props.taskData.packSpecs
        data.openForm.producer = props.taskData.producer
        data.openForm.sellUnit = props.taskData.sellUnit

        data.openForm.sellerId = props.taskData.objectId
        data.openForm.sellerName = props.taskData.objectName
      }
    }

    // 确定
    const handlSubmit = () => {
      data.openRef.validate((valid) => {
        if (valid) {
          handleFormData();
        }
      });
    };

    const handleFormData = () => {
      var obj = {},
        msg = "",
        commit = undefined;
      if (props.typeEdit === "create") {
        obj = {
          headId: data.openForm.headId,
          headName: data.openForm.headName,
          planId: data.openForm.planId,
          sellerId: data.openForm.sellerId,
          productId: data.openForm.productId,
          tradePrice: Number(data.openForm.tradePrice),
          remark: data.openForm.remark,
          allocationAgentId:Number(data.openForm.allocationAgentId),
            saleTaskId:Number(data.openForm.saleTaskId),
            saleTaskNo:data.openForm.saleTaskNo
        };
        if (data.typeTitle === "新建商业营销要素") {
          msg = "创建成功";
          commit = api.businessAgreement.BUSINESSAGREEMENT_CREATE;
        }
        if (data.typeTitle === "编辑商业营销要素") {
          msg = "编辑成功";
          commit = api.businessAgreement.BUSINESSAGREEMENT_UPDATE;
          obj.id = data.openForm.id;
        }
      }

      if (props.typeEdit === "change") {
        obj = {
          headId: data.openForm.headId,
          headName: data.openForm.headName,
          tradePrice: Number(data.openForm.tradePrice),
          remark: data.openForm.remark,
          id: data.openForm.id,
        };
        msg = "变更成功";
        commit = api.businessAgreement.BUSINESSAGREEMENT_CHANGE;
      }
      commit(obj).then((res) => {
        if (res.code === 0) {
          currentInstance.proxy.customMessage({
            type: "success",
            message: msg,
          });
          context.emit("succsess");
          close();
        } else {
          currentInstance.proxy.customMessage({
            type: "error",
            message: res.msg,
          });
        }
      });
    };

    return {
      ...toRefs(data),
      handleHead,
      priceConfirm,
      priceFocus,
      priceClear,
      querySearchSeller,
      handleSelecSeller,
        sellerBlur,
      handleTo,
      productConfirm,
      onInput,
      productClear,
      close,
      handleRemove,
      open,
      handlSubmit,
      handleFormData,
      taskBlur,
      taskFocus,
      taskClear,
      taskConfirm,
    };
  },
};
</script>

<style scoped>
/* @import url(); 引入css类 */
</style>
